from flask_restful import Resource, reqparse
from werkzeug.security import check_password_hash, generate_password_hash

from restful.api__.session import add_session, del_session, login_required_current_user_generate
from restful.model.delete import DeleteInstance
from restful.model.query import QueryOneInstance
from restful.model.tables import User, Role, Personal
from restful.model.update import UpdateInstance
from restful.response import ResponseSuccess, ResponseNotFound, ResponseUnauthorized, ResponseConflict

def NewUser(username,password):
    user = User(username=username, password=generate_password_hash(password))
    UpdateInstance(user)
    UpdateInstance(Personal(uid=user.id))
    UpdateInstance(Role(uid=user.id))

def DelUser(uid):
    DeleteInstance(QueryOneInstance(Personal,{"uid":uid}))
    DeleteInstance(QueryOneInstance(Role,{"uid":uid}))
    DeleteInstance(QueryOneInstance(User,{"id":uid}))


class Register(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, help="用户名不能为空")
        parser.add_argument('password', required=True, help="必须大小写数字及特殊字符")
        form = parser.parse_args()

        data = QueryOneInstance(User,{'username':form['username']})

        if data:
            return ResponseConflict("用户已存在")

        NewUser(username=form['username'],password=form['password'])
        return ResponseSuccess(msg="注册用户成功")

class Login(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', required=True, help="用户名不能为空")
        parser.add_argument('password', required=True, help="必须大小写数字及特殊字符")
        form = parser.parse_args()

        user = QueryOneInstance(User,{'username':form['username']})

        if not user:
            return ResponseNotFound("用户不存在")

        if not check_password_hash(user.password,form['password']):
            return ResponseUnauthorized("用户密码错误")

        add_session(user.id)
        return ResponseSuccess(msg="登录成功")

    @login_required_current_user_generate
    def delete(self,current_user):
        del_session()
        return ResponseSuccess(msg="退出登录")

